<template>
  <div class="page-card">
    <div class="table-toolbar">
      <el-input
        v-model="search"
        placeholder="输入姓名或教师编号"
        clearable
        style="max-width: 240px"
        @keyup.enter="handleSearch"
        @clear="handleSearch"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
      <el-button type="primary" @click="openDialog()">
        <el-icon><Plus /></el-icon>
        新增教师
      </el-button>
    </div>

    <el-table :data="teachers" border v-loading="loading">
      <el-table-column prop="teacher_no" label="教师编号" width="140" />
      <el-table-column prop="teacher_name" label="姓名" width="140" />
      <el-table-column label="性别" width="80">
        <template #default="{ row }">
          {{ genderMap[row.gender] }}
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="联系电话" width="140" />
      <el-table-column prop="email" label="邮箱" width="180" />

      <el-table-column prop="subject_code" label="教学科目" width="140" />
      <el-table-column prop="job_title" label="职称" width="120" />
      <el-table-column label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '在职' : '离职' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openDialog(row)">编辑</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="pagination.size"
        :current-page="pagination.page"
        :total="pagination.total"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="640px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="form-grid">
        <el-form-item label="教师编号" prop="teacher_no">
          <el-input v-model="form.teacher_no" />
        </el-form-item>
        <el-form-item label="姓名" prop="teacher_name">
          <el-input v-model="form.teacher_name" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender">
            <el-option v-for="item in genderOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="birth_date">
          <el-date-picker v-model="form.birth_date" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="身份证号" prop="id_card">
          <el-input v-model="form.id_card" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="教学科目" prop="subject_code">
          <el-input v-model="form.subject_code" />
        </el-form-item>
        <el-form-item label="职称" prop="job_title">
          <el-input v-model="form.job_title" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option v-for="item in teacherStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { Search, Plus } from '@element-plus/icons-vue'
import { createTeacher, deleteTeacher, getTeacherList, updateTeacher } from '@/api/users'

import type { Teacher } from '@/types/users'

import { genderOptions, teacherStatusOptions } from '@/constants/options'

const loading = ref(false)
const saving = ref(false)
const teachers = ref<Teacher[]>([])

const search = ref('')
const pagination = reactive({ page: 1, size: 10, total: 0 })

const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref<FormInstance>()
const form = reactive({
  id: 0,

  teacher_no: '',
  teacher_name: '',
  gender: 1,
  birth_date: '',
  id_card: '',
  phone: '',
  email: '',
  subject_code: '',
  job_title: '',
  status: 1
})

const rules: FormRules = {

  teacher_no: [{ required: true, message: '请输入教师编号', trigger: 'blur' }],
  teacher_name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
}

const genderMap = computed(() =>
  genderOptions.reduce<Record<number, string>>((acc, cur) => {
    acc[cur.value as number] = cur.label
    return acc
  }, {})
)

const dialogTitle = computed(() => (isEdit.value ? '编辑教师' : '新增教师'))

const loadTeachers = async () => {
  loading.value = true
  try {
    const skip = (pagination.page - 1) * pagination.size
    const res = await getTeacherList({ skip, limit: pagination.size })
    const keyword = search.value.trim().toLowerCase()
    teachers.value = res.items.filter((item: any) => {
      if (!keyword) return true
      return (
        item.teacher_name.toLowerCase().includes(keyword) ||
        item.teacher_no.toLowerCase().includes(keyword)
      )
    })
    pagination.total = keyword ? teachers.value.length : res.total
  } catch (error: any) {
    ElMessage.error(error?.message || '加载教师数据失败')
  } finally {
    loading.value = false
  }
}

const handlePageChange = (page: number) => {
  pagination.page = page
  loadTeachers()
}

const handleSearch = () => {
  pagination.page = 1
  loadTeachers()
}

const resetForm = () => {
  Object.assign(form, {
    id: 0,
    teacher_no: '',
    teacher_name: '',
    gender: 1,
    birth_date: '',
    id_card: '',
    phone: '',
    email: '',
    subject_code: '',
    job_title: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

const openDialog = (row?: Teacher) => {
  resetForm()
  if (row) {
    isEdit.value = true
    Object.assign(form, row)
  } else {
    isEdit.value = false
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  saving.value = true
  try {
    if (isEdit.value) {
      await updateTeacher(form.id, { ...form })
    } else {
      await createTeacher({ ...form } as any)
    }
    ElMessage.success('保存成功')
    dialogVisible.value = false
    loadTeachers()
  } catch (error: any) {
    ElMessage.error(error?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

const handleDelete = async (row: Teacher) => {
  await ElMessageBox.confirm(`确认删除教师【${row.teacher_name}】吗？`, '提示', { type: 'warning' })
  try {
    await deleteTeacher(row.id)
    ElMessage.success('已删除')
    loadTeachers()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

onMounted(() => {
  loadTeachers()
})
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: var(--spacing-md);
}
</style>